package com.blue.alipay.utils.http;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * xml工具类
 * @author miklchen
 *
 */
public class XMLUtil {

	private static final String XML_BEGIN = "<xml>";
	private static final String XML_END = "</xml>";

	/**
	 * 将map转换为xml格式
	 * @param map
	 * @return
	 */
	public static String mapToXML(SortedMap<String, String> map) {
		StringBuffer sb = new StringBuffer();
		sb.append(XML_BEGIN);
		Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append(XML_END);
		return sb.toString();
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param xml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map<String, String> XMLToMap(String xml) throws JDOMException, IOException {
		if (null == xml || "".equals(xml)) {
			return null;
		}
		// 过滤以外的非法字符<xml></xml>
		if (xml.indexOf(XML_BEGIN) != -1 && xml.indexOf(XML_END) != -1) {
			xml = xml.substring(xml.indexOf(XML_BEGIN), xml.indexOf(XML_END) + XML_END.length());
		}

		Map<String, String> m = new HashMap<String, String>();
		InputStream in = new ByteArrayInputStream(xml.getBytes());
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List<Element> list = root.getChildren();
		Iterator<Element> it = list.iterator();
		while (it.hasNext()) {
			Element e = it.next();
			String k = e.getName();
			String v = "";
			List<Element> children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			m.put(k, v);
		}
		//关闭流
		in.close();
		return m;
	}

	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	private static String getChildrenText(List<Element> children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator<Element> it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List<Element> list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	/**
	 * 获取xml编码字符集
	 * @param strxml
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	public static String getXMLEncoding(String strxml) throws JDOMException, IOException {
		InputStream in = new ByteArrayInputStream(strxml.getBytes());
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		in.close();
		return (String) doc.getProperty("encoding");
	}

	public static void main(String[] args) {
		try {
			System.out.println(XMLToMap(
					"<?xml version=\"1.0\" encoding=\"UTF-8\"?><alipay><is_success>T</is_success><request><param name=\"_input_charset\">UTF-8</param><param name=\"service\">single_trade_query</param><param name=\"partner\">2088121206235635</param><param name=\"out_trade_no\">16391325593845761</param></request><response><trade><additional_trade_status>DAEMON_CONFIRM_CLOSE</additional_trade_status><buyer_email>jz_qa_zfb_account@daojia.com</buyer_email><buyer_id>2088221871997451</buyer_id><discount>0.00</discount><flag_trade_locked>0</flag_trade_locked><gmt_close>2017-01-05 16:47:26</gmt_close><gmt_create>2017-01-05 15:23:13</gmt_create><gmt_last_modified_time>2017-01-05 16:47:26</gmt_last_modified_time><gmt_payment>2017-01-05 15:23:13</gmt_payment><gmt_refund>2017-01-05 16:47:26.606</gmt_refund><is_total_fee_adjust>F</is_total_fee_adjust><operator_role>B</operator_role><out_trade_no>16391325593845761</out_trade_no><payment_type>1</payment_type><price>0.59</price><quantity>1</quantity><refund_fee>0.59</refund_fee><refund_flow_type>3</refund_flow_type><refund_id>31176902</refund_id><refund_status>REFUND_SUCCESS</refund_status><seller_email>bjwbdj@daojia.com</seller_email><seller_id>2088121206235635</seller_id><subject>到家家政-小时工</subject><to_buyer_fee>0.59</to_buyer_fee><to_seller_fee>0.59</to_seller_fee><total_fee>0.59</total_fee><trade_no>2017010521001004450205825124</trade_no><trade_status>TRADE_CLOSED</trade_status><use_coupon>F</use_coupon></trade></response><sign>fAQ22KODqIkUFJVdkASBbw1BChXls/1Y67TKGV8v64UUmdzQkxn65ygRzH+Gu9bE7liB/g3V3kN480aWlIxhawF91Lgl9+mlwf2+OYYGR9F+3KA0x9cLcstSKix0bT11XaTD3uVTP+P+9yrhI82aD3d6fpfhYAWN6V3SnSMfjHE=</sign><sign_type>RSA</sign_type></alipay>"));
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
	}
}
